package main

import (
	"crypto/tls"
	"crypto/x509"
	"fmt"
	mqtt "github.com/eclipse/paho.mqtt.golang"
	"io/ioutil"
	"time"
)

func main() {
	var broker = "192.168.107.179"
	var port = 8883
	opts := mqtt.NewClientOptions()
	opts.AddBroker(fmt.Sprintf("tcp://%s:%d", broker, port))
	opts.SetClientID("go_mqtt_client")
	opts.SetUsername("magus")
	opts.SetPassword("openplant")
	tlsConfig := NewTlsConfig()
	opts.SetTLSConfig(tlsConfig)
	c := mqtt.NewClient(opts)
	token := c.Connect()
	status := token.WaitTimeout(time.Second * 20)
	if token.Error() != nil {
		fmt.Println(token.Error(), "reconnection in 5 second")
		time.Sleep(time.Second * 5)
		return
	}
	if status {
		fmt.Println("MQTT broker connection successfully")
	}
	defer c.Disconnect(250)

}

func NewTlsConfig() *tls.Config {
	certpool := x509.NewCertPool()
	ca, err := ioutil.ReadFile("ca.pem")
	if err != nil {
		fmt.Println(err.Error())
	}
	certpool.AppendCertsFromPEM(ca)
	return &tls.Config{
		RootCAs: certpool,
	}
}
